package org.csu.jpetstore.controller;

import org.csu.jpetstore.domain.Cart;
import org.csu.jpetstore.domain.Item;
import org.csu.jpetstore.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@SessionAttributes("cart")
@RequestMapping("cart/")
public class CartController {
    @Autowired
    private Cart cart;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("viewCart")
    public String viewCart(Model model) {
        model.addAttribute("cart", cart);
        return "cart/Cart";
    }

    @GetMapping("addItemToCart")
    public String viewCart(String workingItemId, Model model) {
        if (cart.containsItemId(workingItemId)) {
            cart.incrementQuantityByItemId(workingItemId);
        } else {
            boolean isStock = categoryService.isItemInStock(workingItemId);
            Item item = categoryService.getItem(workingItemId);
            cart.addItem(item, isStock);
        }
        model.addAttribute("cart", cart);
        return "cart/Cart";
    }

    @GetMapping("removeItem")
    public String removeItem(String itemId, Model model) {
        Item item = cart.removeItemById(itemId);
        if (item == null) {
            String tip = "删除失败";
            model.addAttribute("tip", tip);
        }
        return "cart/Cart";
    }
}
